(function (window, page) {
    let $ = window.$;
    let $$ = window.$$;

    function executeSteps(list) {
        return list.reduce((p, c) => p.then(r => c()), Promise.resolve(true));
    }

    function delay(time = 100) {
        return new Promise((rs, rj) => {
            setTimeout(() => rs(), time);
        })
    }

    function check(callback, count = 3, interval = 2000) {
        return new Promise((rs, rj) => {
            let i = 0;
            let handle = setInterval(() => {
                let r = callback();
                if (r) {
                    clearInterval(handle);
                    rs(true);
                } else {
                    i++;
                    if (i >= count) {
                        clearInterval(handle);
                        rj('timeout');
                    }
                }
            }, interval);
        })
    }

    function trigger(elem, type = 'change') {
        let evt = document.createEvent('Event');
        evt.initEvent(type, false, false);
        elem.dispatchEvent(evt);
    }

    let steps = [
        () => $('#complaint_type_copyright').click(),
        () => delay(1000),
        () => $('#affected_entity_self').click()
    ];

    let mylist = [
        {
            "title": "【顾俊】富士 X-T30，入门的价格和机身，顶级的画质和性能",
            "link": "https://www.bilibili.com/video/BV1ix411o7Gk"
        },
        {
            "title": "【顾俊】最好的vlog相机，或许，就是你随身携带的手机？！",
            "link": "https://www.bilibili.com/video/BV13x411o7zT"
        }];

    let youtubelist = [
        {
            "title": "富士 X-T30，入门的价格和机身，顶级的画质和性能",
            "vid": "https://www.youtube.com/watch?v=N0Oe0DcNcj0"
        },
        {
            "title": "最好的vlog相机，或许，就是你随身携带的手机？！",
            "vid": "https://www.youtube.com/watch?v=UGZpFM7K2k8&t=101s"
        }
    ];

    youtubelist.filter((v, i) => Math.floor(i / 10) == page).map((y, i) => {
        let found = mylist.find(m => m.title == '【顾俊】' + y.title);
        if (!found) {
            console.error('NOT FOUND', y.title);
        }
        return {
            title: y.title,
            youtube: y.vid,
            bilibili: found && found.href || 'NOT FOUND'
        }
    }).forEach((v, i) => {
        steps.push(() => {
            let steps = [];
            let videos = $$('#video-info-div .video-detail-wrapper:not(.hid)');
            let parent = videos[videos.length - 1];

            console.log(parent.id);

            let videoUrl = $('.video-url', parent);

            steps.push(() => videoUrl.value = v.youtube);
            steps.push(() => trigger(videoUrl));
            steps.push(() => check(() => $('.yt-alert-success', parent).textContent.startsWith('视频所有权')));
            steps.push(() => $('.issue-type', parent).value = 'X');
            steps.push(() => trigger($('.issue-type', parent)));

            steps.push(() => delay(1000));
            steps.push(() => $('[name^=issue_detail_X_]', parent).value = v.title);
            steps.push(() => $('[name^=issue_detail_X_link_]', parent).value = `${v && v.bilibili || 'NOT FOUND'}`);
            steps.push(() => $('[name^=issue_detail_position_]', parent).click());
            steps.push(() => $('.add-video-button', parent).click());
            steps.push(() => delay(1000));

            return executeSteps(steps);
        })

    });

    steps = steps.concat(
        () => $('#owner_desplay_name').value = '_布',
        () => $('#request_title').value = '视频制作者',
        () => $('#request_name').value = '彭大伟',
        () => $('#address1').value = '上海市寻花路523弄问柳巷',
        () => $('#city').value = '上海市',
        () => $('#state').value = '上海市',
        () => $('#zip').value = '20001',
        () => $('#country').value = 'CN',
        () => trigger($('#country')),
        () => $('#phone').value = '17536751219'
    );

    executeSteps(steps).then(r => {
        console.log('done')
    });


})(window, 0);